import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from "../components/Login";
import Home from "../components/Home"
import Welcome from "../components/Welcome";
import UserList from "../views/admin/UserList";

Vue.use(VueRouter)

const routes = [
  {
    path: "/",
    redirect: "/login"
  },
  {
    path: "/login",
    component: Login,
    meta:{
      title: '登录'
    }
  },
  {
    path: "/home",
    component: Home,
    redirect: "/welcome",
    children:[
      {
        path: '/welcome',
        component:Welcome,
        meta:{
          title: '欢迎'
        }
      },
      {
        path: '/user',
        component:UserList,
        meta:{
          title: '用户列表'
        }
      },
      {
        path: '/sport',
        name: 'Sport',
        meta:{
          title: '运动'
        },
        component: ()=> import ("../views/front/Sport")
      },
      {
        path: '/rights',
        name: 'Rights',
        meta:{
          title: '权限'
        },
        component: ()=> import("../views/admin/Rigths")
      },
      {
        path: '/calories',
        name: 'Calories',
        meta:{
          title: '卡路里'
        },
        component: ()=> import("../views/front/Calories")
      },
      {
        path: '/food',
        name: 'Food',
        meta:{
          title: '食物'
        },
        component: ()=> import("../views/front/Food")
      },
      {
        path: '/goods',
        name: 'Goods',
        meta:{
          title: '商品'
        },
        component: ()=> import("../views/front/Goods")
      },
      {
        path: '/introduction',
        name: 'Introduction',
        meta:{
          title: '运动科普'
        },
        component: ()=> import("../views/front/Introduction")
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

//出问题时使用
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location,onResolve,onReject){
  if (onResolve || onReject) return originalPush.call(this,location,onResolve,onReject)
  return originalPush.call(this,location).catch(err => err)
}

//挂载路由导航守卫
router.beforeEach((to,from,next)=>{
  //to将要访问
  //from从哪访问
  //next接着干next(url) 重定向到url上 next() 继续访问 to路径
  if (to.path == '/login') return next();
  //获取user
  const userFlag = window.sessionStorage.getItem("user"); //取出user
  if (!userFlag) return next('/login'); //无值，返回登陆
  next(); //符合要求 放行
})
export default router
